package cn.base.web.support.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import java.io.IOException;

/**
 *  多次读取request的inputStream内容
 *  read之后才可以调用以下方法：
 *  参考：ContentCachingRequestWrapper
 * String requestBody = new String(requestWrapper.getContentAsByteArray());
 *  String responseBody = new String(responseWrapper.getContentAsByteArray());
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter(urlPatterns = "/*", asyncSupported = true)
@Slf4j
//@Component
public class MultiReadHttpServletRequestFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("MultiReadHttpServletRequestFilter initialized");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        MultiReadHttpServletRequestWrapper contentCachingRequestWrapper = new MultiReadHttpServletRequestWrapper((HttpServletRequest) servletRequest);
        filterChain.doFilter(contentCachingRequestWrapper, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
